package com.zhangyj.sso;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.zhangyj.impl.UserContext;
import com.zhangyj.util.AlgorithmUtil;

public class CookieUserSSO implements SSO {

	@Override
	public String authenticateUser(HttpServletRequest request) {
		String lgnName = null;
		Cookie cs[] = request.getCookies();
		for (int i = 0; i < cs.length;i++) {
			Cookie c = cs[i];
			if (c.getName().equals("_ssid")) {
				lgnName = AlgorithmUtil.desDecryptToString(c.getValue(), AlgorithmUtil.fieldDesKey);//String ssid = AlgorithmUtil.desEncryptToString(lgnName.getBytes(), fieldDesKey);
				break;
			}
		}
		return lgnName;
	}

	@Override
	public boolean isSessionValid(UserContext userContext, HttpServletRequest request) {
		String lgnName = authenticateUser(request);
		if (lgnName != null &&  !UserContext.isAnonymity(request)  && lgnName.equals(userContext.getLgnName())) {
			return true;
		}
		return false;
	}

}
